<template>
  <div>
    <a-modal :width="500" title="修改密码" v-model="visible" @ok="handleOk">
      <div class="error">
        密码规则：密码长度必须大于或等于12位，且包含数字、大小写字母及特殊字符
      </div>
      <table class="form mt10 mb10">
        <tr>
          <td class="label need w120">旧密码</td>
          <td><a-input-password v-model.trim="oldPwd"></a-input-password></td>
        </tr>
        <tr>
          <td class="label need">新密码</td>
          <td><a-input-password v-model.trim="newPwd"></a-input-password></td>
        </tr>
        <tr>
          <td class="label need">新密码确认</td>
          <td><a-input-password v-model.trim="newPwdConfirm"></a-input-password></td>
        </tr>
      </table>
    </a-modal>
  </div>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      oldPwd: '',
      newPwd: '',
      newPwdConfirm: ''
    }
  },
  mounted () {
    this.reset()
  },
  methods: {
    reset () {
      this.oldPwd = ''
      this.newPwd = ''
      this.newPwdConfirm = ''
    },
    open () {
      this.visible = true
    },
    close () {
      this.visible = false
    },
    checkPwd (pwd) {
      const minLength = 12
      const hasNumber = /[0-9]/
      const hasUpperCase = /[A-Z]/
      const hasLowerCase = /[a-z]/
      const hasSpecialChar = /[\W_]/

      if (pwd.length < minLength ||
        !hasNumber.test(pwd) ||
        !hasUpperCase.test(pwd) ||
        !hasLowerCase.test(pwd) ||
        !hasSpecialChar.test(pwd)) {
        return false
      }

      return true
    },
    handleOk () {
      if (this.oldPwd.length === 0) {
        this.$warning({ title: '请输入旧密码' })
        return
      }
      if (this.newPwd.length === 0) {
        this.$warning({ title: '请输入新密码' })
        return
      }
      if (!this.checkPwd(this.newPwd)) {
        this.$warning({ title: '新密码不符合规则' })
        return
      }
      if (this.newPwdConfirm.length === 0) {
        this.$warning({ title: '请再次输入新密码' })
        return
      }
      if (this.newPwdConfirm !== this.newPwd) {
        this.$warning({ title: '两次输入的密码不一致' })
        return
      }

      this.$http.post('/zg-system/user/pwd/change', {
        oldPwd: this.genPwd(this.oldPwd),
        newPwd: this.genPwd(this.newPwd)
      }, () => {
        this.close()
        this.$info({ title: '操作成功！' })
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
